package controllers

import dao._
import models.Tables._
import org.joda.time.DateTime
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents}
import tool.FormTool
import utils.Utils

import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global
import implicits.Implicits._
import argonaut._
import Argonaut._
import ArgonautShapeless._

import scala.concurrent.Future

/**
 * Created by Administrator on 2019/8/7
 */
class MemberController @Inject()(cc: ControllerComponents)(
  implicit val memberDao: MemberDao,
  implicit val accountDao: AccountDao,
  implicit val companyMemberDao: CompanyMemberDao,
  implicit val specialMemberDao: SpecialMemberDao,
) extends
  AbstractController(cc) {

  def accountCheck = Action.async { implicit request =>
    val data = FormTool.accountForm.bindFromRequest.get
    val bsF = Future.sequence(
      List(
        memberDao.accountExist(data.account),
        companyMemberDao.accountExist(data.account),
        specialMemberDao.accountExist(data.account),
      )
    )
    bsF.zip(accountDao.selectById1).map { case (bs, admin) =>
      if (bs.exists(x=>x)) {
        Ok(Json.obj("valid" -> false))
      } else {
        val valid = if (data.account == admin.account) false else true
        Ok(Json.obj("valid" -> valid))
      }
    }
  }

  def add = Action.async { implicit request =>
    val data = FormTool.memberForm.bindFromRequest().get
    val row = MemberRow(0, data.account, data.password, new DateTime())
    memberDao.insert(row).map { x =>
      Ok(Json.toJson("success!"))
    }
  }

  def all = Action.async { implicit request =>
    memberDao.selectAll.map { x =>
      val array = x.map(_.asJson)
      Ok(array.asJson)
    }
  }

  def delete = Action.async { implicit request =>
    val data = FormTool.idForm.bindFromRequest().get
    memberDao.deleteById(data.id).map { x =>

      Ok(Json.obj("result"->"success"))
    }
  }

  def getById = Action.async { implicit request =>
    val data = FormTool.idForm.bindFromRequest().get
    memberDao.selectById(data.id).map { x =>
      Ok(x.asJson)
    }
  }

  def update = Action.async { implicit request =>
    val data = FormTool.memberForm.bindFromRequest().get
    memberDao.selectByAccountSome(data.account).flatMap { dbUser =>
      val row = dbUser.copy(password = data.password)
      memberDao.update(row).map { x =>
        Ok(Json.obj("result"->"success"))
      }
    }
  }


}
